package node_category

import (
	"encoding/json"
	"gitee.com/theegg/go-brick/app/service/app"
	"gitee.com/theegg/go-brick/app/service/help/credis"
	"github.com/go-redis/redis/v8"
)

var CacheKeyPrefix = TableName + "_"

// 获取单个数据
// @param id int64 数据的id
// @return *Nodes
func GetAllItemsFromCache() ([]*NodeCategory, error) {
	key := CacheKeyPrefix + "all"
	redisOp := credis.New().Tag(TableName)
	data, errGet := redisOp.TGet(key)
	if errGet != nil {
		if errGet == redis.Nil {
			data, errDb := GetAllItemsFromDb()
			if errDb != nil {
				return nil, app.NewError(errDb)
			}

			jsonData, _ := json.Marshal(data)

			_, errSet := redisOp.TSet(key, jsonData)
			if errSet != nil {
				panic(errGet)
			}

			return data, nil
		}
		panic("Redis-" + errGet.Error())
	}

	var returnData []*NodeCategory
	jsonErr := json.Unmarshal(data, &returnData)
	if jsonErr != nil {
		return nil, app.NewError(jsonErr)
	}

	return returnData, nil
}

// @title FlushTag
// @description 删除tag上所有的
func FlushCacheByTag() {
	redisOp := credis.New().Tag(TableName)
	redisOp.FlushTag()
}
